package com.example.Arithmetic.Lettcode;


import com.example.Arithmetic.Arithmetic.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 日期：2023/10/14
 * 时间：17:28
 * 描述：二叉树层序遍历z字形
 */
public class E06Lettcode103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root==null) {
            return list;
        }
        ArrayDeque<TreeNode> arrayDeque = new ArrayDeque();
        arrayDeque.offer(root);
        boolean fa=true;
        while (!arrayDeque.isEmpty()){
            LinkedList integerList = new LinkedList<>();
            for (int i=arrayDeque.size();i>0;i--) {
                TreeNode poll = arrayDeque.poll();
                if (fa){
                    integerList.offerLast(poll.val);
                } else{
                    integerList.offerFirst(poll.val);
                }
                if (poll.left!=null) {
                    arrayDeque.offer(poll.left);
                }
                if (poll.right!=null) {
                    arrayDeque.offer(poll.right);
                }
            }
            list.add(integerList);
            fa=!fa;
        }
        return list;
    }
}
